package smodul

import (
	"WeChatMGRA/modul"
	"WeChatMGRA/requests"
	"errors"
	"gitee.com/yutiandou/wdtools/wdlog"
	"github.com/jinzhu/gorm"
	"strings"
	"sync"
	"time"
)


//var allgroup = sync.Map{}

type Robots struct {
	gorm.Model
	Wcid string `gorm:"type:varchar(255);unique_index;not null"`
	Creator string `gorm:"not null"`
	NickName string `gorm:"type:varchar(255)"`
	TransmitHash string `gorm:"type:varchar(128);not null"`
	CurrentOwner string `gorm:"type:varchar(128)"`
	CurrentGroup string `gorm:"type:varchar(128)"`
	MaxGroups int `gorm:"default:0;not null"`
	StartTime int64 `gorm:"default:0;not null"`
	WorkTime int64 `gorm:"default:0;not null"`
	WorkStat int `gorm:"default:1;not null"` //  2：主播 3：群播
	Stat int `gorm:"default:1;not null"` //1：机器人正常  2：机器人删除
	AllLiveGroups string `gorm:"type:text"`
	Wid string  `gorm:"type:varchar(255)"`
	NowGroups int `gorm:"default:0;not null"`
	WorkProgress int `gorm:"default:1;not null"` // 100:开始转播，101：暂停转播
	Online int `gorm:"default:1;not null"` // 1:离线  2：在线

	MsgPipe chan * modul.ReceiveData `json:"-" gorm:"-"`
	CurrentListWcid sync.Map `gorm:"-" json:"-"`
	LiveGroupsWcid sync.Map `gorm:"-" json:"-"`
	Broadcasst *BroadcastManage  `gorm:"-" json:"-"`
	//MaxMsgList int32 `gorm:"-",json:"-"`
}

//InsertRobot ..插入机器人
func (r * Robots)InsertRobot()bool {
	if err := MysqlDB.Create(r).Error ;wdlog.Error(err){
		return false
	}
	return true
}
//AddWorkGroup ..插入群组  1：已存在  2：正常添加  3：群数超限
func (r * Robots)AddWorkGroup(wcid string)int{
	if _,ok:=r.LiveGroupsWcid.Load(wcid);ok{
		return 1
	}
	r.NowGroups=0
	r.LiveGroupsWcid.Range(func(key,value interface{})bool{
		r.NowGroups++
		return true
	})
	if r.NowGroups >= r.MaxGroups{
		return 3
	}
	allwx,err:=requests.GetChatRoomMember(r.Wid,wcid)
	if wdlog.Error(err){
		return 4
	}
	for _,v := range allwx{
		if strings.Count(v.NickName,"着调生活机器人")>0{
			return 5
		}
	}
	r.LiveGroupsWcid.Store(wcid,true)
	return 2
}
//RemoveWorlGroup 移除工作群聊  1：当前工作群没有该群  2:成功从工作群组移除该群
func( r* Robots)RemoveWorlGroup(wcid string)int{
	if _,ok:=r.LiveGroupsWcid.Load(wcid);!ok{
		return 1
	}
	r.LiveGroupsWcid.Delete(wcid)
	r.NowGroups--
	return 2
}
//RangeWorkGroup 遍历工作群组
func (r * Robots)RangeWorkGroup(call func(wcid string)bool) {
	jishu := 0
	r.LiveGroupsWcid.Range(func(key, value interface{}) bool {
		if value.(bool) {
			if !call(key.(string)){
				//r.LiveGroupsWcid.Delete(key.(string))
			}
		}
		if jishu >= 100{
			return false
		}
		jishu ++
		return true
	})
	jishu = 0

}
//Select 查找一个机器人
func (r * Robots)Select(online int)error{
	if err:= MysqlDB.Where("  online = ? and  stat = ? ",online,1).First(r).Error;err!=nil{
		return err
	}
	r.StrGroupsToSliGroups()
	return nil
}
func (r * Robots)Updata(online int)int64{
		return MysqlDB.Model(r).Where("  online = ? and  stat = ? ",online,1).Updates(r).RowsAffected
}
func (r * Robots)Save(online int)int64{
	return MysqlDB.Where("  online = ? and  stat = ? ",online,1).Save(r).RowsAffected
}

//UpdataRobot_Config 配置机器人开始工作 return  1：配置成功 2：当前机器人不存在或占用  3:服务器错误
func(r * Robots) UpdataRobot_Config()int{
	r.AllLiveGroups = ""
	r.LiveGroupsWcid.Range(func(key,value interface{})bool{
		if value.(bool){
			r.AllLiveGroups+=key.(string)
			r.AllLiveGroups += ";"
		}
		return true
	})
	r.CurrentOwner = ""
	r.CurrentListWcid.Range(func(key,value interface{})bool{
		if value.(bool){
			r.CurrentOwner+=key.(string)
			r.CurrentOwner += ";"
		}
		return true
	})
	MysqlDB.Model(r).Update(r)
	return 1
}
//ForcedUpdate 固定刷新
func(r * Robots)ForcedUpdate(){
	r.AllLiveGroups = ""
	r.LiveGroupsWcid.Range(func(key,value interface{})bool{
		if value.(bool){
			r.AllLiveGroups+=key.(string)
			r.AllLiveGroups += ";"
		}
		return true
	})
	r.CurrentOwner = ""
	r.CurrentListWcid.Range(func(key,value interface{})bool{
		if value.(bool){
			r.CurrentOwner+=key.(string)
			r.CurrentOwner += ";"
		}
		return true
	})
	if rs:= MysqlDB.Save(r).RowsAffected;rs!=1{
		wdlog.Warning("机器人未保存成功：",*r)
	}
}
func(r * Robots)StrGroupsToSliGroups(){
	allgroups := strings.Split(r.AllLiveGroups,";")
	for k,_:= range  allgroups{
		r.LiveGroupsWcid.Store(allgroups[k],true)
	}
	allcurrent := strings.Split(r.CurrentOwner,";")
	for k,_:= range  allcurrent{
		r.CurrentListWcid.Store(allcurrent[k],true)
	}
}

//DataInit 数据初始化
func(r * Robots)DataInit(){
	//r.AllLiveGroups = ""
	//r.Wid = ""
	//r.CurrentOwner = ""
	//r.CurrentGroup = ""
	//r.WorkStat = 1
	//r.WorkProgress = 1
	//r.StartTime = 0
	//r.WorkTime = 0
	//r.NowGroups = 0
	//r.MaxGroups = 0
	//r.TransmitHash = ""
	r.Online = 1
	if rs:= MysqlDB.Save(r).RowsAffected;rs!=1{
		wdlog.Warning("机器人未保存成功：",*r)
	}
}

func (r * Robots)TransmitMsg(){
	r.MsgPipe = make(chan * modul.ReceiveData,128)
	for{
		if r.WorkStat ==1{
			break
		}
		select {
		case data:= <- r.MsgPipe:
			r.ReceiveTypeMsg(data)
			modul.GiveRecvdata(data)
			time.Sleep(time.Second)
		default:
			time.Sleep(time.Second*5)
		}


	}
}
//Get_All_Offline_Robots ..查询所有机器人
func Get_All_Offline_Robots()([]Robots,error){
	rs:=make([]Robots,0)
	MysqlDB.Select("id,nick_name,online").Where("stat = 1").Find(&rs)
	if MysqlDB.Error!=gorm.ErrRecordNotFound && wdlog.Error(MysqlDB.Error){
		return nil,errors.New("查询错误，未发现可供使用的机器人")
	}
	return rs,nil
}
//Get_All_Working_Robots ..查询所有工作中的机器人
func Get_All_Working_Robots()([]*Robots,error){
	rs:=make([]*Robots,0)
	err:=MysqlDB.Where("stat = 1 and online = 2").Find(&rs).Error
	if err!=gorm.ErrRecordNotFound && err!=nil{
		return nil,err
	}
	return rs,nil
}


